package com.ai.wxy.spring.auth.security;

import com.ai.wxy.spring.auth.dto.UrlRoleDTO;
import com.ai.wxy.spring.auth.service.IUrlRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * URL 权限匹配
 *
 * @author 石头
 * @Date 2019/10/30
 * @Version 1.0
 **/
@Slf4j
public class URLFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private FilterInvocationSecurityMetadataSource  superMetadataSource;
    private IUrlRoleService urlRoleService;

    /**Ant path 匹配*/
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public URLFilterInvocationSecurityMetadataSource(FilterInvocationSecurityMetadataSource  superMetadataSource,IUrlRoleService urlRoleService){
        this.superMetadataSource = superMetadataSource;
        this.urlRoleService = urlRoleService;
    }
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        // 从DB或其他存储中获取url权限列表
        List<UrlRoleDTO> urlRoleList = urlRoleService.getAllUrlRoles();
        for (UrlRoleDTO urlRole:urlRoleList){
            // 匹配到了
            if (antPathMatcher.match(urlRole.getUrl(),url)){
                return SecurityConfig.createList(urlRole.getRole());
            }
        }

        // 返回代码定义的默认配置
        return superMetadataSource.getAttributes(object);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
